import os.path
import re
from common.read import read
import yaml

files = read.read_img()


class YamlUtil:

    def __init__(self):
        self.data_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"data/")

    #读取yaml文件内容
    def read_yaml(self,yaml_name,key_name=None):
        with open(self.data_path + yaml_name,"r",encoding="utf-8") as f:
            value = yaml.safe_load(f)
            if key_name:
                return value[key_name]
            return value

    #读取yaml格式的测试用例的内容,用作pytest.mark.paramtrize参数化
    def read_testcase_yaml(self,yaml_name,key_name=None):
        case_value = self.read_yaml(yaml_name,key_name)[0]
        new_case = []
        for value in case_value["case_info"]:
            new_case.append({"request_info":case_value["request_info"],"case_info":value})
        return new_case





    #写入extract.yaml文件
    def write_extra_yaml(self,data):
        with open(self.data_path + "extract.yaml","a",encoding="utf-8") as f:
            #先读取文件内容字典格式，要是有相同的key则覆盖，要是有不同的key则新增
            old_value = self.read_extra_yaml()
            if old_value:
                for key,value in data.items():
                    old_value[key] = value
                self.clear_extract_yaml()
                #把新的数据写入extract.yaml文件中
                yaml.dump(data=old_value,stream=f,allow_unicode=True,sort_keys=False)
            else:
                yaml.dump(data=data,stream=f)


    #读取extract.yaml文件内容
    def read_extra_yaml(self):
        with open(self.data_path +"extract.yaml","r",encoding="utf-8") as f:
            value = yaml.safe_load(f)
            return value

    #清空extract.yaml文件内容,也不是全部清空，key值存在的则替换掉，不同的保留了
    def clear_extract_yaml(self):
        with open(self.data_path + "extract.yaml","w",encoding="utf-8") as f:
            f.truncate()


if __name__ == "__main__":
    pass
    # f =YamlUtil().read_extra_yaml()
    # print(f)
    # data ={"code":888,"pp":"hjjk"}
    # print(YamlUtil().write_extra_yaml(data))

